# -*- coding: utf-8 -*-
import base64
import sys
import urllib

import cStringIO
import urllib2
from macpath import join

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.http import HttpResponse
from django.http import HttpRequest
from django.views.generic.edit import FormView

from core.forms import ComparerForm
from core.hash_utils import Hash
import json
from django.core  import serializers
class HomeView(FormView):
    form_class = ComparerForm
    template_name = "home.html"
    success_url = '/'
    def form_valid(self, form):
        data = self.get_context_data() 
        data['form'] = form
        first_image = form.cleaned_data['first_image']
        second_image = form.cleaned_data['second_image']

        first_image_url = self.save_image(first_image)
        second_image_url = self.save_image(second_image)

        first_image_hasher = Hash(first_image)
        second_image_hasher = Hash(second_image)

        first_image_score = first_image_hasher.ahash()
        second_image_score = second_image_hasher.ahash()

        s1 =  first_image_hasher.calc_scores()
        s2 = second_image_hasher.calc_scores()
        vector = []
        for h1, h2 in zip(s1, s2):
            vector.append(Hash.calc_difference(h1[1], h2[1]))
        data['is_duplicates'] = Hash.predict(vector)

        data['first_image'] = {
            'image': first_image_url,
            'score': first_image_score,
            'score_decimal': int(first_image_score, base=2)
        }

        data['second_image'] = {
            'image': second_image_url,
            'score': second_image_score,
            'score_decimal': int(second_image_score, base=2)
        }

        diff = 0
        for i in range(len(second_image_score)):
            if first_image_score[i] != second_image_score[i]:
                diff += 1
        data['diff_score'] = diff
        return self.render_to_response(data)

    def save_image(self, image):
        url = default_storage.save(image.name, ContentFile(image.read()))
        return url
    def test( self,request ):
        img_base64='get'
        if(request.method=='POST'):
            img_base64 = 'post'
        return HttpResponse(img_base64)
    #将图片特征值返回
    def hash_image( self,request ):
        img_base64='get'
        commonHelper = Common()
        img_base64 = request.POST.get('img_base64','')
        if(img_base64==''):
            return commonHelper.json_out({
                'error': 1,
                'msg': '图片base64值错误',
                'img_hash': ''
            })
        try:
            image = base64.b64decode(img_base64)
            file = cStringIO.StringIO(image)
            first_image_hasher = Hash(file)
            first_image_score = first_image_hasher.ahash()
            return commonHelper.json_out({
                'error': 0,
                'msg': '',
                'img_hash': first_image_score
            })
        except:
            info = sys.exc_info()
            return commonHelper.json_out({
                'error': 2,
                'msg': join(info[0],info[1]),
                'img_hash': ''
            })
    #将图片特征值返回
    def hash_image_url( self,request ):
        commonHelper = Common()
        img_url = request.POST.get('img_url','')
        if(img_url==''):
            return commonHelper.json_out({
                'error': 1,
                'msg': '图片url错误',
                'img_hash': ''
            })
        try:
            image = urllib2.urlopen(img_url).read()
            file = cStringIO.StringIO(image)
            first_image_hasher = Hash(file)
            first_image_score = first_image_hasher.ahash()
            return commonHelper.json_out({
                'error': 0,
                'msg': '',
                'img_hash': first_image_score
            })
        except:
            info = sys.exc_info()
            return commonHelper.json_out({
                'error': 2,
                'msg': join(info[0],info[1]),
                'img_hash': ''
            })
    #对评论进行预验证
    def comment_check( self,request ):
        commonHelper = Common()
        comment = request.GET.get('comment','')
        if(comment==''):
            return commonHelper.json_out({
                'error': 1,
                'msg': '评论为空',
                'result': 0
            })
        from bayes.test import check
        try:
            result = check(comment)
            if result == 1:
                msg = "垃圾评论"
            else:
                msg = "正常评论"
            return commonHelper.json_out({
                'error': 0,
                'msg': msg,
                'result': result
            })
        except:
            info = sys.exc_info()
            return commonHelper.json_out({
                'error': 2,
                'msg': "系统发生异常",
                'result': 0
            })


class Common:
    def json_out(self,data):
        json_data = json.dumps(data)
        return HttpResponse(json_data,content_type="application/json")
